package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.Category;
import com.entity.ShopGoods;
import com.service.CategoryService;
import com.service.ShopGoodsService;
import com.util.CookieUtil;
import com.util.PageTool;
import com.util.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Controller
public class ShopGoodsController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ShopGoodsService shopGoodsService;

    @Autowired
    private HttpSession session;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/getGoodsByPage")
    public String getGoodsByPage(String currentPageNo, Model model, String name) {
        PageTool pageTool = new PageTool();
        int count = shopGoodsService.getGoodsCount(name);
        pageTool.setTotalCount(count);
        pageTool.setCurrentPageNo(currentPageNo);
        List<ShopGoods> list = shopGoodsService.findGoodsByPage(pageTool.getCurrentPageNo(), pageTool.getPageSize(), name);
        model.addAttribute("goodsList", list);
        model.addAttribute("pageTool", pageTool);
        return "GoodsList";
    }

    @GetMapping("readyEditGoods")
    public String readyEditGoods(@Param("id") Integer id, Model model) {
        ShopGoods goods = shopGoodsService.findByPrimaryKey(id);
        //一级分类的集合
        List<Category> oneCategoryList = categoryService.findCategoryByParentId("0");

        if (goods.getCategoryLevel1Id() != null) {
            List<Category> twoCategoryList = categoryService.findCategoryByParentId(goods.getCategoryLevel1Id().toString());
            model.addAttribute("twoCategoryList", twoCategoryList);
        }
        if (goods.getCategoryLevel2Id() != null) {
            List<Category> threeCategoryList = categoryService.findCategoryByParentId(goods.getCategoryLevel2Id().toString());
            model.addAttribute("threeCategoryList", threeCategoryList);
        }

        model.addAttribute("goods", goods);
        model.addAttribute("oneCategoryList", oneCategoryList);
        return "editGoods";
    }

    @PostMapping("doEditGoods")
    public void readyEditGoods(ShopGoods goods, HttpServletResponse response) throws IOException {
        int num = shopGoodsService.modifyByPrimaryKeySelective(goods);
        if (num > 0) {
            jsMessage(response, "修改成功");
        } else {
            jsMessage(response, "修改失败");
        }

    }

    @RequestMapping("addGoods")
    public void addGoods(ShopGoods goods, HttpServletResponse response, MultipartFile photo) throws IOException {
//        String autoName = UUID.randomUUID().toString().replace("-", "");
//        System.out.println("autoName:" + autoName);
        // 得到文件的名称
        String fileName = photo.getOriginalFilename();
        // 扩展名(略)
        // 得到上传的指定盘符
        File f = new File("D:/WorkSpace/GitWorkSpace/shopMall/src/main/webapp/files/" + fileName);
//        System.out.println(f.getPath());
        // 上传
//        System.out.println(fileName + "-----------");
        photo.transferTo(f);
//        System.out.println(goods);
        goods.setFileName(fileName);
        int i = shopGoodsService.addSelective(goods);
        if (i > 0) {
            jsMessage(response, "添加成功");
        } else {
            jsMessage(response, "添加失败");

        }
    }

    @ResponseBody
    @RequestMapping("removeGoodsById")
    public int removeGoodsById(HttpServletResponse response, Integer id) throws IOException {
        int i = shopGoodsService.removeByPrimaryKey(id);
        return i;
    }

    @RequestMapping("cart")
    public String cart(Model model) {
        List<ShopGoods> list = null;
        String dbStr = redisUtil.get(token());
        if (dbStr != null) {
            list = JSON.parseArray(dbStr, ShopGoods.class);
        }
        model.addAttribute("cart", list);
        return "cart";
    }

    @RequestMapping("getGoodsById")
    public String getGoodsById(Integer id, Model model) {
        ShopGoods goods = shopGoodsService.findByPrimaryKey(id);
        model.addAttribute("goods", goods);
        return "goodsDetail";
    }

    @RequestMapping("addCart")
    public String addCart(Integer id, Integer num) throws NullPointerException {
        if (!"".equals(id)) {

            Map<Integer, ShopGoods> mp = (Map<Integer, ShopGoods>) session.getAttribute("mp");
            if (mp == null) {
                mp = new LinkedHashMap<Integer, ShopGoods>();
            }
            ShopGoods goods = null;
            if (mp.containsKey(id)) {
                goods = mp.get(id);
                goods.setNumber(num + goods.getNumber());
            } else {
                goods = shopGoodsService.findByPrimaryKey(id);
                goods.setNumber(num);
            }
            if (null != goods) {
                mp.put(id, goods);
            }
            session.setAttribute("mp", mp);
        }
        return "redirect:cart";
    }

    @ResponseBody
    @RequestMapping("changeCart")
    public boolean changeCart(Integer id, Integer num, Integer[] ids) {
        Map<Integer, ShopGoods> mp = (Map<Integer, ShopGoods>) session.getAttribute("mp");
        if (mp == null) {
            mp = new LinkedHashMap<Integer, ShopGoods>();
        }
        ShopGoods goods = null;
        if (id != null && num == 0) {
            mp.remove(id);
        } else if (id != null && num > 0) {
            if (mp.containsKey(id)) {
                goods = mp.get(id);
                goods.setNumber(num);
                mp.put(id, goods);
            }
        } else if (null != ids & ids.length > 0) {
            for (Integer i : ids) {
                if (mp.containsKey(i)) {
                    mp.remove(i);
                }
            }
        }

        session.setAttribute("mp", mp);
        return true;
    }

    private String token() {
        return CookieUtil.readCookieToken(request);
    }

    @RequestMapping("addCart2")
    public String addCart2(Integer id, Integer num, Model model) throws NullPointerException {
        System.out.println(id+num);
        if (!"".equals(id)) {
            List<ShopGoods> list = null;
            String dbStr = redisUtil.get(token());
            if (null == dbStr) {
                list = new ArrayList<ShopGoods>();
            } else {
                list = JSON.parseArray(dbStr, ShopGoods.class);
            }
            ShopGoods goods = null;
            boolean flag = false;
            for (int index = 0; index < list.size(); index++) {
                if (list.get(index).getId().equals(id)) {
                    goods = list.get(index);
                    goods.setNumber(goods.getNumber() + num);
                    list.set(index, goods);
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                goods = shopGoodsService.findByPrimaryKey(id);
                goods.setNumber(num);
                if (null != goods) {
                    list.add(goods);
                }
            }
            String saveStr = JSON.toJSONString(list);
            redisUtil.set(token(), saveStr);
//            redisUtil.expire("cart", 7 * 24 * 60 * 60);
//            model.addAttribute("cart", list);
//            session.setAttribute("cart", list);
        }
        return "redirect:cart";
    }

    @ResponseBody
    @RequestMapping("changeCart2")
    public boolean changeCart2(Integer id, Integer num, Integer[] ids, Model model) {
        List<ShopGoods> list = null;
        String dbStr = redisUtil.get(token());
        if (null == dbStr) {
            list = new ArrayList<ShopGoods>();
        } else {
            list = JSON.parseArray(dbStr, ShopGoods.class);
        }
        ShopGoods goods = null;
        for (int index = 0; index < list.size(); index++) {
            if (list.get(index).getId().equals(id)) {
                if (null != id && num > 0) {
                    goods = list.get(index);
                    goods.setNumber(num);
                } else if (id != null && num == 0) {
                    list.remove(index);
                    break;
                }
            }
        }
        if (null != ids && ids.length > 0) {
            for (Integer i : ids) {
                for (int index = 0; index < list.size(); index++) {
                    if (list.get(index).getId().equals(i)) {
                        list.remove(index);
                    }
                }
            }
        }
//        session.setAttribute("cart", list);
        String saveStr = JSON.toJSONString(list);
        redisUtil.set(token(), saveStr);
//        model.addAttribute("cart", list);
        return true;
    }

    private void jsMessage(HttpServletResponse response, String mes) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.write("<script>alert('" + mes + "');location.href='getGoodsByPage'</script>");
    }
}
